package org.liveboardgames.agricola.business;

import java.util.ArrayList;
import java.util.List;

import org.liveboardgames.agricola.access.IGameDao;
import org.liveboardgames.agricola.business.helper.GameHelper;
import org.liveboardgames.agricola.business.updater.CardUpdater;
import org.liveboardgames.agricola.business.updater.FarmTileUpdater;
import org.liveboardgames.agricola.business.updater.GameUpdater;
import org.liveboardgames.agricola.controller.AgricolaUpdateAdapter;
import org.liveboardgames.agricola.domain.Change;
import org.liveboardgames.agricola.domain.Game;
import org.liveboardgames.agricola.domain.card.Card;
import org.liveboardgames.agricola.domain.common.Peep;
import org.liveboardgames.agricola.domain.farm.FarmTile;

public class PeepServiceImpl implements IPeepService {

  private IGameDao gameDao;

  public void setGameDao(IGameDao gameDao) {
    this.gameDao = gameDao;
  }

  public void dropPeep(Long gameId, Long peepId, Long cardId) {

    List<Change> changes = new ArrayList<Change>();

    Game game = gameDao.load(gameId);

    GameHelper gameHelper = new GameHelper();

    Card card = gameHelper.findCard(game, cardId);
    Peep peep = gameHelper.findPeep(game, peepId);
    new CardUpdater(card, changes).addPeep(peep);

    FarmTile farmTile = gameHelper.getFarmTileContainingPeep(game, peep);
    new FarmTileUpdater(farmTile, changes).removePeep(peep);

    GameUpdater gameUpdater = new GameUpdater(game, changes);
    gameUpdater.setHasPlayerPlayedPeep(true);

    gameDao.save(game);

    new AgricolaUpdateAdapter().publishGameUpdates(gameId, changes);
  }

}
